<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    function getJson (method, url, params) {
      let promise = new Promise((resolve, reject) => {
        let xhr = new XMLHttpRequest()
        let str = ''
        let res = []
        for (let key in params) {
          str = key + '=' + params[key]
        }
        str = res.join('&') // 拼接params
        method = method.toUpperCase()
        if (method === 'GET') {
          xhr.open(method, url + '?' + str)
          xhr.send()
        }
        if (method === 'POST') {
          xhr.open(method, url)
          xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
          xhr.send(str)
        }
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) {
            if (xhr.status === 200) {
              resolve(JSON.parse(xhr.responseText))
            } else {
              reject(xhr.statusText)
            }
          }
        }
      })
      return promise
    }
    getJson('POST', 'http://localhost:3000/api/addUser', {
      name: '方现伟',
      age: '20岁'
    }).then((val) => {
      console.log(val);
    })
  </script>
</body>

</html>